package com.myhome.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.config.constant.R;
import com.myhome.domain.SysUser;
import com.myhome.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @Author QYiXin
 * @Date 2021 10 11 15 27
 **/
@RestController
@Api(tags = "用户管理")
@RequestMapping("/users")
public class SysUserController {
    @Autowired
    SysUserService sysUserService;

    @GetMapping
    @ApiOperation("查询用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数"),
            @ApiImplicitParam(name = "mobile", value = "员工的手机号码"),
            @ApiImplicitParam(name = "fullname", value = "员工的全名称"),
    })
    @PreAuthorize("hasAuthority('sys_user_query')")
    public R<Page<SysUser>> getPageUsers(@ApiIgnore Page<SysUser> page, String mobile, String fullName) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysUser> result = sysUserService.getPageUsers(page, mobile, fullName);
        return R.ok(result);
    }

    @PostMapping
    @ApiOperation("用户新增")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sysUser", value = "sysUser 的json数据")
    })
    @PreAuthorize("hasAuthority('sys_user_create')")
    public R addUser(@RequestBody SysUser sysUser) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        sysUser.setCreateBy(userId);
        Boolean isAdd = sysUserService.addUser(sysUser);
        if (isAdd) {
            return R.ok("新增成功");
        }
        return R.fail("新增失败");
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    @PreAuthorize("hasAuthority('sys_user_delete')")
    public R deleteUser(@RequestBody Long[] ids) {
        Boolean isDelete = sysUserService.removeUserWithRoles(ids);
        if (isDelete) {
            return R.ok("删除成功");
        }
        return R.fail("删除失败");
    }

    @PatchMapping
    @ApiOperation("修改用户")
    public R updateUser(@RequestBody SysUser sysUser){
        Boolean isUpdate = sysUserService.updateUser(sysUser);
        if (isUpdate) {
            return R.ok();
        }
        return R.fail("修改失败");
    }
}
